/**     
* @Title: XmlParser.java   
* @Package me.crawler.parser   
* @Description: TODO   
* @author xaoyaoyao
* @date 2019年1月19日 上午10:11:22
*/
package me.crawler.parser;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.util.Assert;

import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import me.crawler.entity.SpiderSeed;
import me.crawler.util.InfoExtractorUtil;
import me.crawler.util.XStreamUtil;

/**
 * @ClassName: XmlParser
 * @Description: TODO
 * @author xaoyaoyao
 * @date 2019年1月19日 上午10:11:22
 * 
 */
@Slf4j
@Builder
public class XmlParser {

	/** html文本 **/
	private String htmlTxt;

	/** 种子 **/
	List<SpiderSeed> seeds;

	public <T> T parse(Class<T> clazz) {
		log.debug(">>>>>>>> htmlTxt >> {}", htmlTxt);
		log.debug(">>>>>>>> seed >> {}", seeds);
		if (CollectionUtils.isEmpty(seeds)) {
			return null;
		}
		Assert.notNull(htmlTxt, "Html text cannot be empty.");
		Assert.notNull(clazz, "Class cannot be empty.");
		for (SpiderSeed seed : seeds) {
			T t = parse(seed, clazz);
			if (null != t) {
				return t;
			}
		}
		return null;
	}

	private <T> T parse(SpiderSeed seed, Class<T> clazz) {
		Assert.notNull(seed, "SpiderSeed cannot be empty.");
		String xslt = seed.getTemplate();
		Assert.notNull(xslt, "XSLT(Template) cannot be empty.");
		String xml = InfoExtractorUtil.transform(htmlTxt, xslt);
		log.debug(">>>>>>>> xml >> {}", xml);
		return XStreamUtil.xmlToBean(xml, clazz);
	}
}